package model

import (
	"fmt"
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Praise struct {
	User User `gorm:"foreignkey:Uid"`
	BaseModel
	Aid     int    `gorm:"type:int;not null" json:"aid"`
	Uid     int    `gorm:"type:int;not null" json:"uid"`
	Status int `gorm:"type:int; not null" json:"status"`
}

// 新增点赞
func CreatePraise(data *Praise)int  {
	err := db.Create(&data).Error
	if err !=nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

// 查询用户是否点赞了这篇文章 有值200
func IsPraiseArt(uid int , aid int)(Praise,int) {
	var praise Praise
	db.Select("id,status").Where(&Praise{Aid: aid, Uid: uid}).First(&praise)
	if praise.ID > 0  {
		return praise,errmsg.SUCCSE
	}
	return praise,errmsg.ERROR
}


// 取消点赞更新
func SavePraise(data *Praise,uid int) int  {
	var praise Praise
	var maps = make(map[string]interface{})
	maps["status"] = data.Status
	err = db.Model(&praise).Where(&Praise{Aid: data.Aid, Uid: uid}).Update(maps).Error
	if err != nil{
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

// 查询用户所有的文章点赞id的数组
func GetUserArtId(uid int)([]int,int) {
	praise := make([]*Praise,0)
	err = db.Debug().Select("aid").Where("uid = ? AND status = ?", uid, 0).Find(&praise).Error
	if err != nil {
		return make([]int, 0),errmsg.ERROR
	}

	fmt.Printf("praise:%#v\n",praise)

	var uidList []int
	for _, v := range praise {
		uidList = append(uidList,v.Aid)
	}
	fmt.Printf("uidList:%#v\n",uidList)

	return uidList,errmsg.SUCCSE
}

// 查询是否点赞过文章
func FindPraise(slice []int, val int) (int, bool) {
	for i, item := range slice {
		if item == val {
			return i, true
		}
	}
	return -1, false
}

//  一篇文章的点赞列表
func GetArtPraiseList(aid int, pageSize int, pageNum int)([]Praise,int) {
	var praiseList []Praise

	err = db.Debug().Preload("User", func(db *gorm.DB) *gorm.DB {
		return db.Select("username,id,created_at")
	}).Limit(pageSize).Offset((pageNum-1)*pageSize).Where("aid = ?", aid).Where("status = ?", 0).Find(&praiseList).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return make([]Praise,0),errmsg.ERROR
	}
	fmt.Printf("v ==== %+v \n", praiseList)
	return praiseList,errmsg.SUCCSE
}

